<template>
	<BasicModal v-bind="$attrs" z-index="1000" style="z-index:999" @register="registerModal" title="选择定位"
		@ok="confirmSelect" :helpMessage="['提示1', '提示2']">
		<!-- 		<a-form-item label="" style="width: 100%">
			<JSearchSelect placeholder="选择定位" v-model:value="selectValue" :dictOptions="dictOptions" @input="onSearch"
				@blur="selectAddress">
			</JSearchSelect>
		</a-form-item> -->

		<div id="container">

		</div>
		<!-- <div class="info">
			<div class="input-item">
				<div class="input-item-prepend">
					<span class="input-item-text" style="width:8rem;">请输入关键字</span>
				</div>
				<a-input id='tipinput' style="width:50%" @change="selectAddress" v-model:value="selectValue" type="text"
					placeholder="输入关键字搜索" />
			</div>
		</div> -->

		<div id="pickerBox">
			<input id="pickerInput" placeholder="输入关键字选取地点" />
			<div id="poiInfo"></div>
		</div>
	</BasicModal>
</template>
<script lang="ts" setup>
	import AMapLoader from '@amap/amap-jsapi-loader';
	import { defineComponent, ref } from 'vue';
	import { useMessage } from '/@/hooks/web/useMessage';
	import { BasicModal, useModalInner } from '/@/components/Modal';
	import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
	const selectValue = ref('');
	const asyncSelectValue = ref('');
	let dictOptions = ref([] as Array)
	let value = ref<string>('');
	const emit = defineEmits(['register', 'successConfirm']);
	let marker = null;
	const { createMessage } = useMessage();
	function confirmSelect() {
		if (form.address == '') {
			return createMessage.warning('请先选择经纬度');;
		}
		emit('successConfirm', form);
		closeModal()
	}


	// 地图实例
	let geocoder, AutoComplete;
	/* 	const onSearch = (obj) => {
			AutoComplete.search(obj.data, (status, result) => {
				let res = result.tips
				let o = {}
				dictOptions.value = []
				dictOptions.value = res.map(i => {
					return { text: i.name, value: i.name }
				})
			});
		}; */
	let map;
	const selectAddress = (obj) => {
		geocoder.getLocation(obj, function (status, result) {
			if (status === 'complete' && result.geocodes.length) {
				var lnglat = result.geocodes[0].location
				console.log(lnglat)
				map.setFitView();
				marker = new AMap.Marker({
					map: map,
					position: [lnglat.lng, lnglat.lat],
				});
				map.setFitView();
				map.add(marker);

			} else {
				console.log('根据地址查询位置失败');
			}
		});
	}
	function setMapMarker() {
		// 自动适应显示想显示的范围区域
		map.setFitView();
		marker = new AMap.Marker({
			map: map,
			position: [form.lng, form.lat],
		});
		map.setFitView();
		map.add(marker);
	}
	// 清除点
	function removeMarker() {
		if (marker) {
			map.remove(marker);
		}
	}


	function poiPickerReady(poiPicker) {
		console.log(2222)
		window.poiPicker = poiPicker;

		var marker = new AMap.Marker();

		var infoWindow = new AMap.InfoWindow({
			offset: new AMap.Pixel(0, -20)
		});
		//选取了某个POI
		poiPicker.on('poiPicked', function (poiResult) {

			var source = poiResult.source,
				poi = poiResult.item,
				info = {
					source: source,
					id: poi.id,
					name: poi.name,
					location: poi.location.toString(),
					address: poi.address
				};

			//marker.setMap(map);
			//infoWindow.setMap(map);
			marker.setPosition(poi.location);
			//infoWindow.setPosition(poi.location);

			//infoWindow.setContent('POI信息: <pre>' + JSON.stringify(info, null, 2) + '</pre>');
			//infoWindow.open(map, marker.getPosition());

			map.setCenter(marker.getPosition());
		});

		/* 	poiPicker.onCityReady(function () {
				poiPicker.suggest('美食');
			}); */
	}

	// 位置信息
	let form = {
		lng: "",
		lat: "",
		address: "",
		adcode: "", //地区编码
	}
	const path = ref([]);
	const current_position = ref([]);
	const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
		setModalProps({ zIndex: 1000 })
		initMap()
	})

	// 选中提示
	function currentSelect(val) {
		// 清空时不执行后面代码
		if (!val) {
			return;
		}
		form = {
			lng: val.location.lng,
			lat: val.location.lat,
			address: val.district + val.address,
			adcode: val.adcode,
		};

	}
	var poiPicker;
	function initMap() {
		window._AMapSecurityConfig = {
			securityJsCode: '2b7f424b6b4c0ca9eade07b4df7edf00',
		}

		AMapLoader.load({
			key: "d363dce36e0cf588721ffa48268bb5fd", // 申请好的Web端开发者Key，首次调用 load 时必填
			version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
			// plugins:[''], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
			AMapUI: {
				version: '1.1',
				plugins: []
			}
		}).then((AMap) => {
			map = new AMap.Map("container", {  //设置地图容器id
				viewMode: "2D",    //是否为3D地图模式
				zoom: 13,           //初始化地图级别
				center: [104.066301, 30.572961], //初始化地图中心点位置
			});
			// 添加插件
			AMap.plugin(["AMap.ToolBar", "AMap.Scale", "AMap.HawkEye", "AMap.Marker", "AMap.Geocoder", "AMap.AutoComplete", "AMap.Geolocation", "AMap.MapType", "AMap.MouseTool"], function () {
				//异步同时加载多个插件
				// 添加地图插件
				map.addControl(new AMap.ToolBar()); // 工具条控件;范围选择控件
				map.addControl(new AMap.Scale()); // 显示当前地图中心的比例尺
				map.addControl(new AMap.HawkEye()); // 显示缩略图
				AutoComplete = new AMap.AutoComplete({ city: "全国" });
				geocoder = new AMap.Geocoder({
					radius: 500, //范围，默认：500
				});
			});
			// 单击
			map.on('click', (e) => {
				console.log(e.lnglat)
				let lnglat = [e.lnglat.lng, e.lnglat.lat];
				form.lng = e.lnglat.lng
				form.lat = e.lnglat.lat
				poiPickerReady(poiPicker);
				removeMarker()
				setMapMarker();
				geocoder.getAddress(lnglat, (status, result) => {
					if (status === "complete" && result.regeocode) {
						form.address = result.regeocode.addressComponent.street + result.regeocode.addressComponent.streetNumber + "," + result.regeocode.formattedAddress

					} else {
						console.log(status, result)
					}
				})

			})
			AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {
				poiPicker = new PoiPicker({
					city: '成都',
					input: 'pickerInput'
				});
				//初始化poiPicker
				poiPickerReady(poiPicker);
			});
		}).catch(e => {
			console.log(e);
		})
	}
</script>

<style>
	#pickerBox {
		position: absolute;
		z-index: 9999;
		top: 50px;
		right: 30px;
		width: 300px;
	}

	#pickerInput {
		width: 200px;
		padding: 5px 5px;
	}

	#poiInfo {
		background: #fff;
	}

	.amap_lib_placeSearch .poibox.highlight {
		background-color: #CAE1FF;
	}

	.amap_lib_placeSearch .poi-more {
		display: none !important;
	}

	#container {
		padding: 0px;
		margin: 0px;
		width: 100%;
		height: 600px;
	}

	.info {
		padding: .5rem .75rem;
		margin-bottom: 1rem;
		border-radius: .25rem;
		position: fixed;
		top: 15rem;
		background-color: white;
		width: auto;
		z-index: 100;
		min-width: 20%;
		border-width: 0;
		right: 40%;
		box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
	}

	.input-item {
		position: relative;
		display: -ms-flexbox;
		display: flex;
		-ms-flex-wrap: wrap;
		flex-wrap: wrap;
		-ms-flex-align: center;
		align-items: center;
		width: 100%;
		height: 3rem;
	}

	.input-item-prepend {
		margin-right: -1px;
	}

	.input-item-text {
		text-align: justify;
		padding: 0.4rem 0.7rem;
		display: inline-block;
		text-justify: distribute-all-lines;
		text-align-last: justify;
		-moz-text-align-last: justify;
		-webkit-text-align-last: justify;
		-ms-flex-align: center;
		align-items: center;
		margin-bottom: 0;
		font-size: 1rem;
		font-weight: 400;
		line-height: 1.5;
		color: #495057;
		text-align: center;
		white-space: nowrap;
		background-color: #e9ecef;
		border: 1px solid #ced4da;
		border-radius: 0.25rem;
		border-bottom-right-radius: 0;
		border-top-right-radius: 0;
	}

	.input-item-text,
	input[type=text],
	input[type=date],
	select {
		height: calc(2.2rem + 2px);
	}
</style>